﻿using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Components.Views;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Excel;
using AJWPFAdmin.Core.Models;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Modules.Common.Views;
using AJWPFAdmin.Services;
using AJWPFAdmin.Services.AppointAPI;
using AJWPFAdmin.Services.EF;
using AJWPFAdmin.Services.Jobs;
using AJWPFAdmin.Services.Models;
using DocumentFormat.OpenXml.Math;
using DocumentFormat.OpenXml.Wordprocessing;
using EntranceGuardManager.Modules.Main.Views;
using Masuit.Tools.Models;
using Masuit.Tools.Reflection;
using MaterialDesignExtensions.Controls;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using static AJWPFAdmin.Core.ExceptionTool;

namespace EntranceGuardManager.Modules.Main.ViewModels
{
    public class UploadFailShippingRecordListViewModel : BindableBase, INavigationAware
    {

        private ShippingRecordExportConfig _exportConfig;
        public ShippingRecordExportConfig ExportConfig
        {
            get { return _exportConfig; }
            set { SetProperty(ref _exportConfig, value); }
        }

        private AJTableFetchOptions _fetchOptions;

        public AJTableFetchOptions FetchOptions
        {
            get
            {
                return _fetchOptions;
            }
            set
            {
                SetProperty(ref _fetchOptions, value);
            }
        }

        private List<AJTableColumnItem> _columns;

        public List<AJTableColumnItem> Columns
        {
            get { return _columns; }
            set { SetProperty(ref _columns, value); }
        }


        private AJTableSearchFormConfig _formConfig;
        public AJTableSearchFormConfig FormConfig
        {
            get { return _formConfig; }
            set { SetProperty(ref _formConfig, value); }
        }

        private DelegateCommand<DataGridRow> _loadingRowCmd;
        public DelegateCommand<DataGridRow> LoadingRowCmd =>
            _loadingRowCmd ?? (_loadingRowCmd = new DelegateCommand<DataGridRow>(ExecuteLoadingRowCmd));

        void ExecuteLoadingRowCmd(DataGridRow row)
        {

        }

        private DelegateCommand<ShippingRecord> _openEmissionStandardImagesPreviewCmd;
        public DelegateCommand<ShippingRecord> OpenEmissionStandardImagesPreviewCmd =>
            _openEmissionStandardImagesPreviewCmd ?? (_openEmissionStandardImagesPreviewCmd = new DelegateCommand<ShippingRecord>(ExecuteOpenEmissionStandardImagesPreviewCmd));

        void ExecuteOpenEmissionStandardImagesPreviewCmd(ShippingRecord parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.EmissionStandardImages);
        }

        private DelegateCommand<ShippingRecord> _openNameplatePreviewCmd;
        public DelegateCommand<ShippingRecord> OpenNameplatePreviewCmd =>
            _openNameplatePreviewCmd ?? (_openNameplatePreviewCmd = new DelegateCommand<ShippingRecord>(ExecuteOpenNameplatePreviewCmd));

        void ExecuteOpenNameplatePreviewCmd(ShippingRecord parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.Nameplate);
        }

        private DelegateCommand<ShippingRecord> _openMachineEnvProtectionLabelPreviewCmd;
        public DelegateCommand<ShippingRecord> OpenMachineEnvProtectionLabelPreviewCmd =>
            _openMachineEnvProtectionLabelPreviewCmd ?? (_openMachineEnvProtectionLabelPreviewCmd = new DelegateCommand<ShippingRecord>(ExecuteOpenMachineEnvProtectionLabelPreviewCmd));

        void ExecuteOpenMachineEnvProtectionLabelPreviewCmd(ShippingRecord parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.MachineEnvProtectionLabel);
        }

        private DelegateCommand<ShippingRecord> _openEngineNameplatePreviewCmd;
        public DelegateCommand<ShippingRecord> OpenEngineNameplatePreviewCmd =>
            _openEngineNameplatePreviewCmd ?? (_openEngineNameplatePreviewCmd = new DelegateCommand<ShippingRecord>(ExecuteOpenEngineNameplatePreviewCmd));

        void ExecuteOpenEngineNameplatePreviewCmd(ShippingRecord parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.EngineNameplate);
        }

        private DelegateCommand<ShippingRecord> _openCarImagePreviewCmd;
        public DelegateCommand<ShippingRecord> OpenCarImagePreviewCmd =>
            _openCarImagePreviewCmd ?? (_openCarImagePreviewCmd = new DelegateCommand<ShippingRecord>(ExecuteOpenCarImagePreviewCmd));

        void ExecuteOpenCarImagePreviewCmd(ShippingRecord parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.CarImage);
        }

        private DelegateCommand<ShippingRecord> _openAttachmentsPreviewCmd;
        public DelegateCommand<ShippingRecord> OpenAttachmentsPreviewCmd =>
            _openAttachmentsPreviewCmd ?? (_openAttachmentsPreviewCmd = new DelegateCommand<ShippingRecord>(ExecuteOpenAttachmentsPreviewCmd));

        void ExecuteOpenAttachmentsPreviewCmd(ShippingRecord parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.Attachments);
        }

        private DelegateCommand<ShippingRecord> _openVehicleLicensePreviewCmd;
        public DelegateCommand<ShippingRecord> OpenVehicleLicensePreviewCmd =>
            _openVehicleLicensePreviewCmd ?? (_openVehicleLicensePreviewCmd = new DelegateCommand<ShippingRecord>(ExecuteOpenVehicleLicensePreviewCmd));

        void ExecuteOpenVehicleLicensePreviewCmd(ShippingRecord parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.VehicleLicense);
        }

        private DelegateCommand<ShippingRecord> _openInCaptureFilePreviewCmd;
        public DelegateCommand<ShippingRecord> OpenInCaptureFilePreviewCmd =>
            _openInCaptureFilePreviewCmd ?? (_openInCaptureFilePreviewCmd = new DelegateCommand<ShippingRecord>(ExecuteOpenInCaptureFilePreviewCmd));

        void ExecuteOpenInCaptureFilePreviewCmd(ShippingRecord parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.InCaptureFile);
        }

        private DelegateCommand<ShippingRecord> _openOutCaptureFilePreviewCmd;
        public DelegateCommand<ShippingRecord> OpenOutCaptureFilePreviewCmd =>
            _openOutCaptureFilePreviewCmd ?? (_openOutCaptureFilePreviewCmd = new DelegateCommand<ShippingRecord>(ExecuteOpenOutCaptureFilePreviewCmd));

        void ExecuteOpenOutCaptureFilePreviewCmd(ShippingRecord parameter)
        {
            ExecuteOpenImagePreviewCmd(parameter.CarNo, parameter.OutCaptureFile);
        }

        void ExecuteOpenImagePreviewCmd(string carNo, string parameter)
        {
            var array = CommonUtil.TryGetJSONObject<string[]>(parameter) ?? Array.Empty<string>();
            if (array.Length > 0)
            {
                array = array.Select(p => _carIdentificationConfig.CompleteFileUrl(carNo, p)).ToArray();
            }

            var @params = new DialogParameters
            {
                { "data", CommonUtil.AJSerializeObject(array) },
            };
            _dialogSvc.ShowDialog(nameof(ImageShowCaseDialog), @params, r =>
            {

            });
        }

        private DelegateCommand<ShippingRecord> _syncGoodsInfoCmd;
        public DelegateCommand<ShippingRecord> SyncGoodsInfoCmd =>
            _syncGoodsInfoCmd ?? (_syncGoodsInfoCmd = new DelegateCommand<ShippingRecord>(ExecuteSyncGoodsInfoCmd));

        async void ExecuteSyncGoodsInfoCmd(ShippingRecord parameter)
        {
            var confirm = await CommonUtil.ShowConfirmDialogAsync(new ConfirmationDialogArguments
            {
                Title = "提示",
                Message = $"确定同步 {parameter.CarNo} 的出场物资信息吗?"
            });

            if (confirm)
            {
                var result = await QinYouGoodsInfoProcessJob.QinYouGoodsInfoProcessQuarztJob.ProcessSingleAsync(db, _appointSvc, parameter);

                if (!result.Success)
                {
                    MessageBox.Show(result.Message, "同步失败", MessageBoxButton.OK);
                    return;
                }

                parameter = result.Data as ShippingRecord;

                db.Entry(parameter).State = EntityState.Modified;

                await db.SaveChangesAsync();

                FetchOptions.RequestRefresh(false);
            }

        }

        private DelegateCommand<ShippingRecord> _editCmd;
        public DelegateCommand<ShippingRecord> EditCmd =>
            _editCmd ?? (_editCmd = new DelegateCommand<ShippingRecord>(ExecuteEditCmd));

        void ExecuteEditCmd(ShippingRecord parameter)
        {
            var @params = new DialogParameters
            {
                { "data", parameter },
                { "category", (CarTypeEnum)((int)parameter.TypeId) },
            };
            _dialogSvc.ShowDialog(nameof(ShippingRecordForm), @params, r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    FetchOptions.RequestRefresh(false);
                }
            });
        }


        private DelegateCommand<ShippingRecord> _deleteCmd;
        public DelegateCommand<ShippingRecord> DeleteCmd =>
            _deleteCmd ?? (_deleteCmd = new DelegateCommand<ShippingRecord>(ExecuteDeleteCmd));

        async void ExecuteDeleteCmd(ShippingRecord parameter)
        {
            var confirm = await CommonUtil.ShowConfirmDialogAsync(new ConfirmationDialogArguments
            {
                Title = "删除确认",
                Message = parameter.Synchronized ? "该条数据已经和线上接口同步,是否继续删除?" : $"即将删除 {parameter.CarNo} ?"
            });

            if (confirm)
            {
                db.ShippingRecords.Remove(parameter);
                await db.SaveChangesAsync();

                FetchOptions.RequestRefresh(false);
            }
        }

        private DelegateCommand<string> _toggleExportConfigCmd;
        public DelegateCommand<string> ToggleExportConfigCmd =>
            _toggleExportConfigCmd ?? (_toggleExportConfigCmd = new DelegateCommand<string>(ExecutetoggleExportConfigCmd));

        void ExecutetoggleExportConfigCmd(string parameter)
        {
            ExportConfig.Open = parameter.Equals("true", StringComparison.OrdinalIgnoreCase);
        }

        private DelegateCommand _exportCmd;
        public DelegateCommand ExportCmd =>
            _exportCmd ?? (_exportCmd = new DelegateCommand(ExecuteExportCmd));

        void ExecuteExportCmd()
        {
            FetchOptions.RequestExport();
        }


        private IDialogService _dialogSvc;
        private DbService db;
        private SystemUserService _sysUserSvc;
        private AppointAPISvc _appointSvc;
        private CarIdentificationConfig _carIdentificationConfig;


        public UploadFailShippingRecordListViewModel(DbService dbIns,
            AppointAPISvc appointSvc,
            SystemUserService sysUserSvc,
            IEventAggregator eventAggregator, IDialogService dialogSvc)
        {
            _sysUserSvc = sysUserSvc;
            _dialogSvc = dialogSvc;
            db = dbIns;
            //eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>().Subscribe(() =>
            //{
            //    Loading = false;
            //    ExportProgress.Loading = false;
            //});

            ExportConfig = new ShippingRecordExportConfig();

            FetchOptions = new AJTableFetchOptions
            {
                FetchOnLoaded = false,
                Handle = async (formCfg, pageCfg) =>
                {

                    var syncFormSchema = FormConfig.Schemas.FirstOrDefault(p => p.Field == nameof(ShippingRecord.Synchronized));

                    var name = FormConfig.Schemas
                .FirstOrDefault(p => p.Field == nameof(ShippingRecord.CarNo)).Value?.ToString();

                    var dates = FormConfig.Schemas
                        .FirstOrDefault(p => p.Field == nameof(ShippingRecord.CreateDate)).Value as ObservableCollection<DateTime?>;

                    var start = dates.FirstOrDefault();
                    var end = dates.LastOrDefault();

                    var shipStartDateSchema = FormConfig.Schemas.FirstOrDefault(p => p.Field == nameof(ShippingRecord.ShipStartDate));

                    var inOrOutFlag = shipStartDateSchema.Value == null ? new int?() : (int)shipStartDateSchema.Value;

                    var emissionStandardFormSchema = FormConfig.Schemas.FirstOrDefault(p => p.Field == nameof(ShippingRecord.EmissionStandard));

                    var emissionStandard = shipStartDateSchema.Value == null ? new EmissionStandard?() : (EmissionStandard)shipStartDateSchema.Value;

                    long[] inWatchHouseIds = null;

                    var inWatchhouseSchema = FormConfig.Schemas.FirstOrDefault(p => p.Field == nameof(ShippingRecord.WatchhouseId));

                    if (inWatchhouseSchema != null
                    && inWatchhouseSchema.Value != null
                    && inWatchhouseSchema.Value
                    is ObservableCollection<AJTableFormSchemaItemOptions> options)
                    {
                        inWatchHouseIds = options.Select(p => (long)p.Value).ToArray();
                    }

                    long?[] outWatchHouseIds = null;

                    var outWatchhouseSchema = FormConfig.Schemas.FirstOrDefault(p => p.Field == nameof(ShippingRecord.OutWatchhouseId));

                    if (outWatchhouseSchema != null
                    && outWatchhouseSchema.Value != null
                    && outWatchhouseSchema.Value
                    is ObservableCollection<AJTableFormSchemaItemOptions> outOptions)
                    {
                        outWatchHouseIds = outOptions.Select(p => new long?((long)p.Value)).ToArray();
                    }

                    var list = await db.ShippingRecords
                    .LikeOrLike(name, p => p.CarNo)
                    .IfWhere(() => start != null && start != DateTime.MinValue, p => p.ShipStartDate >= start)
                    .IfWhere(() => end != null && end != DateTime.MinValue, p => p.ShipEndDate <= end)
                    .IfWhere(() => inOrOutFlag.HasValue && inOrOutFlag == 0, p => p.ShipEndDate == null)
                    .IfWhere(() => inOrOutFlag.HasValue && inOrOutFlag == 1, p => p.ShipEndDate != null)
                    .IfWhere(() => emissionStandard.HasValue, p => p.EmissionStandard == emissionStandard)
                    .IfWhere(() => inWatchHouseIds?.Length > 0, p => inWatchHouseIds.Contains(p.WatchhouseId))
                    .IfWhere(() => outWatchHouseIds?.Length > 0, p => outWatchHouseIds.Contains(p.OutWatchhouseId))
                    .Where(p => p.Synchronized == false)
                    .OrderByDescending(p => p.CreateDate)
                    .ToPagedListAsync(pageCfg.Current, pageCfg.PageSize);

                    if (formCfg.IsExport)
                    {
                        // 如果是导出要补全图片文件路径
                        list.Data.ForEach(r =>
                        {
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.Attachments));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.CarImage));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.VehicleLicense));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.Nameplate));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.EngineNameplate));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.MachineEnvProtectionLabel));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.InCaptureFile));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.OutCaptureFile));
                            r.CompleteFileUrls(_carIdentificationConfig, nameof(r.EmissionStandardImages));
                        });
                    }

                    return new AJTableFetchResult
                    {
                        Total = list.TotalCount,
                        HasNext = list.HasNext,
                        Rows = list.Data
                    };
                }
            };

            var emissionStandardOptions = CommonUtil.EnumToDictionary<EmissionStandard>(null).Select(p => new AJTableFormSchemaItemOptions
            {
                Label = p.Key,
                Value = p.Value
            }).ToList();

            var watchHouseSource = db.Watchhouses.AsNoTracking().ToList();
            var watchHouseOptions = new ObservableCollection<AJTableFormSchemaItemOptions>(watchHouseSource.Select(p => new AJTableFormSchemaItemOptions
            {
                Label = p.Name,
                Value = p.Id,
                OtherData = p
            }));

            FormConfig = new AJTableSearchFormConfig
            {
                Schemas = new ObservableCollection<AJTableSearchFormSchema>
                {
                    new AJTableSearchFormSchema
                    {
                        Label = "车牌号",
                        Field = nameof(ShippingRecord.CarNo),
                        Type = AJTableSchemaType.Input,
                        IsPopular = true,
                    },
                    new AJTableSearchFormSchema
                    {
                        Label = "入口筛选",
                        Field = nameof(ShippingRecord.WatchhouseId),
                        Type = AJTableSchemaType.MultiSelect,
                        IsPopular = true,
                        Options = watchHouseOptions
                    },
                    new AJTableSearchFormSchema
                    {
                        Label = "出口筛选",
                        Field = nameof(ShippingRecord.OutWatchhouseId),
                        Type = AJTableSchemaType.MultiSelect,
                        IsPopular = true,
                        Options = watchHouseOptions
                    },
                    new AJTableSearchFormSchema
                    {
                        Label = "进出筛选",
                        Field = nameof(ShippingRecord.ShipStartDate),
                        Type = AJTableSchemaType.Select,
                        IsPopular = true,
                        Options = new ObservableCollection<AJTableFormSchemaItemOptions>
                        {
                            new AJTableFormSchemaItemOptions
                            {
                                Label = "未出场",
                                Value = 0
                            },
                            new AJTableFormSchemaItemOptions
                            {
                                Label = "已出场",
                                Value = 1
                            }
                        }
                    },
                    new AJTableSearchFormSchema
                    {
                        Label = "排放标准",
                        Field = nameof(ShippingRecord.EmissionStandard),
                        Type = AJTableSchemaType.Select,
                        IsPopular = true,
                        Options = new ObservableCollection<AJTableFormSchemaItemOptions>(emissionStandardOptions)
                    },
                    new AJTableSearchFormSchema
                    {
                        Labels = new string[]{ "入厂日期","出厂日期" },
                        Field = nameof(ShippingRecord.CreateDate),
                        Type = AJTableSchemaType.RangePicker,
                        Value = new ObservableCollection<DateTime?>( new DateTime?[2]
                        {
                            DateTime.Today,
                            DateTime.Today.AddDays(1).AddSeconds(-1)
                        }),
                        IsPopular = true,
                    },
                },
                AdvFilterVisibility = System.Windows.Visibility.Collapsed,
                ExportVisibility = System.Windows.Visibility.Collapsed,
            };
        }

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {

            _carIdentificationConfig = CarIdentificationConfigExt.GetCarIdentificationConfig(db);

            var columns = new List<AJTableColumnItem>
            {
                new AJTableColumnItem
                {
                    Title = "操作",
                    CustomTemplate = new AJTableCustomTemplate
                    {
                        Key = "TableOperatioin"
                    },
                    Fixed = AJTableColumnFixedType.Right,
                    Width = new DataGridLength(160),
                    IsExport = false
                },
                new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.WatchhouseCode),
                        Title = "入口编号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.WatchhouseName),
                        Title = "入口名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.PassagewayCode),
                        Title = "入口道闸编号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.PassagewayName),
                        Title = "入口道闸名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.ShipStartDate),
                        Title = "进厂时间",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.AutoPass),
                        Title = "自动开闸",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return (bool)val ? "是" : "否";
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.OutWatchhouseCode),
                        Title = "出口编号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.OutWatchhouseName),
                        Title = "出口名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.OutPassagewayCode),
                        Title = "出口道闸编号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.OutPassagewayName),
                        Title = "出口道闸名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.ShipEndDate),
                        Title = "出厂时间",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.CarNo),
                        Title = "车牌号码",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.PlateColor),
                        Title = "号牌颜色",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.TruckTypeName),
                        Title = "车辆类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.RegDate),
                        Title = "注册登记日期",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.VIN),
                        Title = "车辆识别代码(VIN)",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.CarBrandModel),
                        Title = "车辆品牌型号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.FuelTypeName),
                        Title = "燃料类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.EmissionStandard),
                        Title = "排放标准",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.NetworkingStatus),
                        Title = "联网状态",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return (bool)val ? "已联网" : "未联网";
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.UsageDescription),
                        Title = "使用性质",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.InGoodsName),
                        Title = "进厂运输货物名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.InGoodsType),
                        Title = "进厂货物类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.InGoodsVolume),
                        Title = "进厂运输量",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return ((decimal)val).ToString("N2");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.OutGoodsName),
                        Title = "出厂运输货物名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.OutGoodsType),
                        Title = "出厂货物类型",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.OutGoodsVolume),
                        Title = "出厂运输量",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return ((decimal)val).ToString("N2");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.FreightUnit),
                        Title = "货运单位",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.TicketCode),
                        Title = "派车单号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.SendOrReceiveFlag),
                        Title = "收发标志",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.Sender),
                        Title = "发货单位",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.Receiver),
                        Title = "收货单位",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.TeamName),
                        Title = "车队名称",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.InCaptureFile),
                        Title = "进场照片",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "InCaptureFileImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.OutCaptureFile),
                        Title = "出厂照片",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "OutCaptureFileImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.Attachments),
                        Title = "随车清单",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "AttachmentsImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.EmissionStandardImages),
                        Title = "排放阶段图片",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "EmissionStandardImagesImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.VehicleLicense),
                        Title = "行驶证",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "VehicleLicenseImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.EnvRegCode),
                        Title = "环保登记编码",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.ProductionDate),
                        Title = "生产日期",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.RegDate),
                        Title = "注册登记日期",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return val == null ? "--"
                                : ((DateTime?)val).GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.CarBrandModel),
                        Title = "车辆品牌型号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.Owner),
                        Title = "车辆所有人(单位)",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.MachineType),
                        Title = "机械种类",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.PIN),
                        Title = "机械环保代码PIN",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.MachineModel),
                        Title = "机械型号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.EngineModel),
                        Title = "发动机型号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.EngineManufacturer),
                        Title = "发动机生产厂",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.EngineNo),
                        Title = "发动机编号",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.Nameplate),
                        Title = "整车(机)铭牌",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "NameplateImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.MachineEnvProtectionLabel),
                        Title = "机械环保信息标签",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "MachineEnvProtectionLabelImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.EngineNameplate),
                        Title = "发动机铭牌",
                        CustomTemplate = new AJTableCustomTemplate
                        {
                            Key = "EngineNameplateImagePreview",
                            IsImage = true,
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.Synchronized),
                        Title = "是否同步",
                        Formatter = new AJTableColumnFormatter
                        {
                            Handler = (val) =>
                            {
                                return (bool)val ? "已同步" : "未同步";
                            }
                        }
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.SyncResult),
                        Title = "同步结果",
                    },
                    new AJTableColumnItem
                    {
                        DataIndex = nameof(ShippingRecord.IsOwnedByCompany),
                        Title = "是否企业自有车辆",
                    },
            };


            _sysUserSvc.CachedColumnsConfig.TryGetValue($"{nameof(UploadFailShippingRecordList).ToLower()}", out var columnNames);
            columnNames ??= new string[0];
            foreach (var column in columns)
            {
                column.Visible = columnNames.Length > 0 ? columnNames.Any(p => p == column.Title) : true;
            }

            Columns = columns;

            // 延迟一下, 不然因为表格没准备好无法触发刷新
            await Task.Delay(600);

            FetchOptions.RequestRefresh(false);
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            _sysUserSvc.SaveColumnsConfig($"{nameof(UploadFailShippingRecordList).ToLower()}",
                Columns.Where(p => p.Visible).Select(p => p.Title).ToArray());
        }

    }
}
